package com.tomkk;

import com.google.gson.Gson;
import com.tomkk.utils.Error;
import com.tomkk.utils.MysqlOperation;
import com.tomkk.utils.Success;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by Tomkk on 2016/6/3.
 */
@WebServlet(name = "CheckUsernameServlet",urlPatterns = "/checkUsername")
public class CheckUsernameServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String sql = "SELECT * FROM user WHERE username  = '"+username+"';";
        MysqlOperation operation = new MysqlOperation();
        operation.checkConn();
        ResultSet resultSet = operation.query(sql);
        Gson gson = new Gson();
        String json = null;
        try {
            if(resultSet.next()){
                json = gson.toJson(new Error(1,""));
            }else{
                json = gson.toJson(new Success(0,""));
            }
        } catch (SQLException e) {
            e.printStackTrace();
            json = gson.toJson(new Error(2,"服务器错误"));
        }
        PrintWriter writer = resp.getWriter();
        writer.print(json);
        writer.flush();
        try {
            operation.closeDB();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
}
